import Vue from 'vue'
import VueRouter from 'vue-router'

//import store from '@/store'
import { routerMode } from '@/utils/env'
import { getStore } from '@/utils/util'
// 在菜单中显示的那部分路由
import * as menu from '@/router/menu/index.js'
// 不在菜单中显示的那部分路由
import invisible from './invisible/index.js'

const getToken = () => {
    //TODO
    let share = JSON.parse(getStore('vuex')) || {};
    if (share.token) {
        return share.token;
    } else {
        return '';
    }
};

Vue.use(VueRouter)

//解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
//push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};
//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject);
  return originalReplace.call(this, location).catch(err => err);
};

const router = new VueRouter({
    routes: [ //入口页
        ...menu.router,
        ...invisible,
    ],
    mode: routerMode,
    strict: process.env.NODE_ENV !== 'production',
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            if (from.meta.keepAlive) {
                from.meta.savedPosition = document.body.scrollTop;
            }
            return {
                x: 0,
                y: to.meta.savedPosition || 0
            }
        }
    }
})


//路由拦截
router.beforeEach((to, from, next) => {
    //TODO
    let token = getToken()
    token = '123'
        // 非登录
    if (to.name !== 'login') {
        // token验证
        if (token) {
            next();
        } else {
            next({ path: '/login' })
        }
    }
    next();
})

export default router;